
package com.oldphonedeals.service.impl;

import com.oldphonedeals.mapper.UserMapper;
import com.oldphonedeals.pojo.User;
import com.oldphonedeals.service.UserService;
import com.oldphonedeals.utils.JwtUtil;
import com.oldphonedeals.dto.UserUpdateDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public User register(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userMapper.save(user);
    }

    @Override
    public String login(User user) {
        User dbUser = userMapper.findByEmail(user.getEmail()).orElse(null);
        if (dbUser != null && passwordEncoder.matches(user.getPassword(), dbUser.getPassword())) {
            return jwtUtil.generateToken(dbUser.getEmail());
        }
        return null;
    }

    @Override
    public User getCurrentUser(String email) {
        return userMapper.findByEmail(email).orElse(null);
    }

    @Override
    public User updateUser(String email, UserUpdateDTO dto) {
        User user = userMapper.findByEmail(email).orElse(null);
        if (user != null) {
            user.setFirstname(dto.getFirstname());
            user.setLastname(dto.getLastname());
            return userMapper.save(user);
        }
        return null;
    }
}
